import React, { Component } from 'react';
import styles from './index.less';

class Captcha extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ...this.initState(),
      refresh: false,
    };
  }

  componentDidMount() {
    this.canvas();
  }

  initState = () => {
    const { targetData } = this.props;
    if (targetData) {
      return {
        fz: this.getRandom(20, 35, targetData.length),
        color: [
          this.getRandom(100, 255, 3),
          this.getRandom(100, 255, 3),
          this.getRandom(100, 255, 3),
          this.getRandom(100, 255, 3),
        ],
      };
    }
  };

  getRandom(max, min, num) {
    const asciiNum = ~~(Math.random() * (max - min + 1) + min);
    if (!num) {
      return asciiNum;
    }
    const arr = [];
    for (let i = 0; i < num; i++) {
      arr.push(this.getRandom(max, min));
    }
    return arr;
  }

  canvas = () => {
    const { width = 160, height = 40 } = this.props;
    const { getRandom } = this;
    const canvas = document.getElementById('bgi');
    const ctx = canvas.getContext('2d');
    canvas.height = height; // 用于清除上次绘制的路径
    ctx.fillStyle = `rgb(${this.getRandom(100, 255, 3).toString()})`;
    ctx.fillRect(0, 0, width, height);
    ctx.strokeStyle = `rgb(${this.getRandom(100, 10, 3).toString()})`;
    for (let i = 0; i < 7; i++) {
      ctx.lineTo(getRandom(width, 0), getRandom(height, 10));
      ctx.moveTo(getRandom(width, 0), getRandom(height, 0));
      ctx.stroke();
    }
  };

  render() {
    const { fz, color, refresh } = this.state;
    const { targetData, width = 160, height = 40 } = this.props;
    return (
      <div className={styles.captchaWrap}>
        <canvas id="bgi" width={width} height={height} />
        <div className={styles.numBox} style={{ width, height, lineHeight: `${height}px` }}>
          {targetData.split('').map((v, i) => (
            <span
              key={i}
              className={styles.itemStr}
              style={{
                fontSize: `${fz[i]}px`,
                color: `rgb(${color[i].toString()})`,
              }}
              onMouseEnter={() => this.setState({ refresh: true })}
            >
              {v}
            </span>
          ))}
        </div>
        {refresh && (
          <div
            style={{ width, height, lineHeight: `${height}px` }}
            className={styles.mask}
            onClick={() => {
              this.setState({ ...this.initState(), refresh: false });
              this.canvas();
            }}
            onMouseLeave={() => {
              this.setState({ refresh: false });
            }}
          >
            看不清？点击刷新
          </div>
        )}
      </div>
    );
  }
}

export default Captcha;
